#include <iostream>
#include <string>
#include "Asyncket.h"

void OnRecv(OVERLAPPED * pOverlapped)
{
	ASYNCKET_CONTEXT * pContext = (ASYNCKET_CONTEXT *)pOverlapped;
	DWORD bytes;
	GetOverlappedResult(pContext->pSender, pOverlapped, &bytes, TRUE);
	std::cout << std::string(pContext->WSABuf.buf, bytes) << std::endl;
	pContext->pSender->Send(pContext->WSABuf.buf, bytes, NULL, NULL);
	pContext->pSender->Recv(pContext->WSABuf.buf, pContext->WSABuf.len, OnRecv, NULL);
}

void OnAccept(OVERLAPPED * pOverlapped)
{
	ASYNCKET_ACCEPT_CONTEXT * pContext = (ASYNCKET_ACCEPT_CONTEXT *)pOverlapped;
	pContext->Accept->Recv(new char[8192], 8192, OnRecv, NULL);
	pContext->Context.pSender->Accept(OnAccept, NULL);
}

int main()
{
	struct sockaddr_in sai;
	ZeroMemory(&sai, sizeof(struct sockaddr_in));
	sai.sin_family = PF_INET;
	sai.sin_port = htons(1266);
	sai.sin_addr.s_addr = INADDR_ANY;
	Asyncket * asyncket = new Asyncket();
	asyncket->Bind((struct sockaddr *)&sai, sizeof(struct sockaddr_in));
	asyncket->Listen(SOMAXCONN);
	asyncket->Accept(OnAccept, NULL);
	std::string cmd;
	while (std::cin >> cmd) {
		if (cmd == "quit") {
			break;
		}
	}
	delete asyncket;
	return 0;
}
